package com.rapida.pet.core;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

import com.rapida.framwork.ISignals;
import com.rapida.framwork.ISlots;
import com.rapida.framwork.PresenterController;

import static com.rapida.pet.core.PetService.CMD;

/**
 * Created by mm on 2015/5/12.
 */
public class PetPresenter extends PresenterController {
    private PetService mPetService;
    private boolean mServiceBound;

    public PetPresenter(MainUI ui) {
        ui.connect(this);
    }

    @Override
    public void onResume() {
    }

    @Override
    public void onPause() {
    }

    public void setCurrentState(PetBehavie.PetState state) {
        mPetService.commond(new CMD(2, state.ordinal()));
    }

    @ISlots(connect = true, name = "trigerEvent")
    public void trigerEvent(PetBehavie.Event event) {
        mPetService.commond(new CMD(1, event.ordinal()));
    }

    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            PetService.PetBinder binder = (PetService.PetBinder) service;
            mPetService = binder.getService();
            mPetService.start();
            mPetService.commond(new PetService.CMD(0, -1));
            mServiceBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mServiceBound = false;
        }
    };

    public void startService(Context context) {
        Intent intent = new Intent(context, PetService.class);
        context.startService(intent);
    }

    public void bindService(Context context) {
        Intent intent = new Intent(context, PetService.class);
        context.bindService(intent, mConnection, Service.BIND_AUTO_CREATE);
    }

    public void unbindService(Context context) {
        if (mServiceBound) {
            context.unbindService(mConnection);
        }
    }
}
